import cv2

# 视频文件路径
input_video_path = r'D:\data\video\cam2.mp4'
output_video_path = r'D:\data\video\cam2-rotate.mp4'

# 读取视频
cap = cv2.VideoCapture(input_video_path)

# 获取视频的宽度、高度和帧率
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
fps = cap.get(cv2.CAP_PROP_FPS)

# 定义编解码器并创建VideoWriter对象
fourcc = cv2.VideoWriter_fourcc(*'avc1')
out = cv2.VideoWriter(output_video_path, fourcc, fps, (height, width))  # 注意宽度和高度交换位置

# 检查是否成功打开视频文件
if not cap.isOpened():
    print("Error: Could not open video.")
    exit()

# 读取视频，旋转每一帧并写入新视频
while cap.isOpened():
    ret, frame = cap.read()
    if ret:
        # 旋转帧
        # 这里以逆时针旋转90度为例
        # 如果需要旋转其他角度或方向，调整cv2.rotate的参数
        rotated_frame = cv2.rotate(frame, cv2.ROTATE_90_CLOCKWISE)

        # 写入旋转后的帧
        out.write(rotated_frame)

        # 可以选择显示旋转的帧（如果需要的话）
        # cv2.imshow('frame', rotated_frame)
        # if cv2.waitKey(1) & 0xFF == ord('q'):
        #     break
    else:
        break

# 释放资源
cap.release()
out.release()
cv2.destroyAllWindows()
